package org.example.company.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.company.entity.AuthUserDetails;
import org.example.response.RespnseResult;
import org.example.response.ResultCode;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
public class AuthenticationFailHandler implements ServerAuthenticationFailureHandler {
    @Override
    public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException e) {
        ServerWebExchange exchange = webFilterExchange.getExchange();
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = response.getHeaders();
        //设置headers
        headers.add("Content-Type","application/json;charset=UTF-8");
        headers.add("Cache-Control","no-store,no-cache,must-revalidate,max-age-8");
        //设置body
        RespnseResult<AuthUserDetails> result = new RespnseResult(ResultCode.UNAUTHORIZED);
        byte[] dataBytes={};
        ObjectMapper mapper = new ObjectMapper();

        try {
            dataBytes= mapper.writeValueAsBytes(result);
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }

        DataBuffer bodyDataBuffer = response.bufferFactory().wrap(dataBytes);
        return response.writeWith(Mono.just(bodyDataBuffer));
    }
}
